<template>
  <div class="lucky-draw-container">
    <!-- 奖项选择区域 -->
    <div class="prize-selector">
      <el-select 
        v-model="selectedPrizeId" 
        placeholder="请选择奖项"
        :disabled="isDrawing"
        style="width: 240px"
      >
        <el-option
          v-for="prize in availablePrizes"
          :key="prize.id"
          :label="`${prize.name} (剩余${prize.remainingCount}个)`"
          :value="prize.id"
          :disabled="prize.remainingCount <= 0"
        />
      </el-select>
    </div>

    <!-- 当前奖项展示 -->
    <div class="prize-display" v-if="currentPrize">
      <h2>{{ currentPrize.name }}</h2>
      <p>{{ currentPrize.description }}</p>
      <div class="prize-image" v-if="currentPrize.image">
        <img :src="currentPrize.image" :alt="currentPrize.name">
      </div>
    </div>
    
    <div class="draw-area">
      <div class="name-rolling" v-if="isDrawing">
        <transition-group 
          name="roll" 
          tag="div"
          class="rolling-names"
        >
          <span 
            v-for="name in rollingNames" 
            :key="name"
            class="rolling-name"
          >
            {{ name }}
          </span>
        </transition-group>
      </div>
      
      <div class="result-display" v-else-if="winners.length">
        <h3>恭喜以下获奖者：</h3>
        <div class="winners-list">
          <div v-for="winner in winners" :key="winner.id" class="winner-item">
            {{ winner.name }}
            <small v-if="winner.department">({{ winner.department }})</small>
          </div>
        </div>
      </div>
      
      <div class="start-hint" v-else>
        <el-empty description="请选择奖项后点击开始抽奖按钮" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { useParticipantsStore } from '../store/participants'
import { usePrizesStore } from '../store/prizes'
import { useHistoryStore } from '../store/history'
import { useSettingsStore } from '../store/settings'
import { ElMessage } from 'element-plus'
import { emitter, isDrawing } from '../utils/eventBus'
import logger from '../utils/logger'

const participantsStore = useParticipantsStore()
const prizesStore = usePrizesStore()
const historyStore = useHistoryStore()
const settingsStore = useSettingsStore()

const selectedPrizeId = ref(null)
const winners = ref([])
const rollingNames = ref([])

// 可用的奖项列表
const availablePrizes = computed(() => {
  logger.debug('Current prizes:', prizesStore.prizes)
  if (!prizesStore.prizes) {
    return []
  }
  return prizesStore.prizes.filter(prize => prize.remainingCount > 0)
})

// 当前选中的奖项
const currentPrize = computed(() => {
  if (!selectedPrizeId.value || !prizesStore.prizes) {
    return null
  }
  return prizesStore.prizes.find(p => p.id === selectedPrizeId.value)
})

// 监听奖项选择变化
watch(selectedPrizeId, (newId) => {
  if (newId) {
    const prize = prizesStore.prizes.find(p => p.id === newId)
    prizesStore.setCurrentPrize(prize)
  } else {
    prizesStore.setCurrentPrize(null)
  }
})

const availableParticipants = computed(() => {
  const excludedIds = new Set(participantsStore.excludedParticipants.map(p => p.id))
  return participantsStore.participants.filter(p => !excludedIds.has(p.id))
})

const rollDuration = computed(() => {
  const speeds = {
    slow: 5000,
    normal: 3000,
    fast: 2000
  }
  return speeds[settingsStore.animationSpeed]
})

const startRolling = () => {
  if (!currentPrize.value) {
    ElMessage.warning('请先选择要抽取的奖项')
    return
  }
  
  if (availableParticipants.value.length < currentPrize.value.count) {
    ElMessage.warning('参与者人数不足')
    return
  }

  isDrawing.value = true
  winners.value = []
  
  // 开始滚动动画
  const rollInterval = setInterval(() => {
    const randomParticipants = getRandomParticipants(3)
    rollingNames.value = randomParticipants.map(p => p.name)
  }, 100)

  // 抽奖结束
  setTimeout(() => {
    clearInterval(rollInterval)
    const selectedWinners = getRandomParticipants(currentPrize.value.count)
    winners.value = selectedWinners
    
    // 记录中奖者
    selectedWinners.forEach(winner => {
      participantsStore.excludeParticipant(winner.id)
    })
    
    // 更新奖项数量
    prizesStore.decrementPrizeCount(currentPrize.value.id)
    
    // 添加历史记录
    historyStore.addRecord({
      prize: currentPrize.value,
      winners: selectedWinners
    })
    
    isDrawing.value = false
    selectedPrizeId.value = null
    
    // 播放音效
    if (settingsStore.soundEnabled) {
      playWinSound()
    }
  }, rollDuration.value)
}

const getRandomParticipants = (count) => {
  const participants = [...availableParticipants.value]
  const result = []
  
  while (result.length < count && participants.length > 0) {
    const randomIndex = Math.floor(Math.random() * participants.length)
    result.push(participants.splice(randomIndex, 1)[0])
  }
  
  return result
}

const playWinSound = () => {
  const audio = new Audio('/win-sound.mp3')
  audio.play()
}

// 监听抽奖事件
onMounted(() => {
  emitter.on('start-lucky-draw', startRolling)
})

onUnmounted(() => {
  emitter.off('start-lucky-draw', startRolling)
})
</script>

<style scoped>
.lucky-draw-container {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

.prize-selector {
  margin-bottom: 20px;
}

.prize-display {
  text-align: center;
  margin-bottom: 40px;
  max-width: 600px;
}

.prize-image {
  margin-top: 20px;
}

.prize-image img {
  max-width: 200px;
  max-height: 200px;
  object-fit: contain;
}

.draw-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 400px;
  width: 100%;
}

.rolling-names {
  font-size: 48px;
  font-weight: bold;
  text-align: center;
}

.rolling-name {
  display: inline-block;
  margin: 10px;
}

.winners-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 20px;
  margin-top: 20px;
}

.winner-item {
  padding: 10px 20px;
  background: #f0f9eb;
  border-radius: 4px;
  color: #67c23a;
}

.winner-item small {
  color: #909399;
  margin-left: 4px;
}

.roll-enter-active,
.roll-leave-active {
  transition: all 0.3s ease;
}

.roll-enter-from,
.roll-leave-to {
  opacity: 0;
  transform: translateY(30px);
}

.start-hint {
  color: #909399;
  text-align: center;
}
</style> 